import datetime

from sqlalchemy import and_

from webapp.extensions import AppException
from webapp.models import Session, db


class SessionService:
    @staticmethod
    def query_all(page=0, size=9999, **kwargs) -> list:
        create_times = kwargs.get('createTime')
        session = kwargs.get('session')
        not_empty = session or create_times
        query = []
        if session:
            query.append((Session.session.like(f'%{session}%')))
        if create_times and len(create_times) >= 2:
            query.append((Session.create_time.between(create_times[0], create_times[1])))
        result = Session.query.filter(*query).paginate(int(page) + 1, per_page=int(size),
                                                       error_out=False)
        return result

    @staticmethod
    def find_by_id(id):
        session = db.session.query(Session).filter(Session.id == id).one_or_none()
        if session is None:
            raise AppException(f'您所操作的对象已不存在!')
        return session

    @staticmethod
    def delete(session_set):
        if session_set:
            for session in session_set:
                db.session.delete(session)
            db.session.commit()

    @staticmethod
    def create(curr_session: Session):
        session = Session.query.filter(Session.session == curr_session.session).one_or_none()
        if session:
            raise AppException(f'{curr_session.session}已存在!')
        curr_session.create_time = datetime.datetime.now()
        db.session.add(curr_session)
        db.session.commit()

    @staticmethod
    def update(curr_session: Session):
        session = Session.query.filter(Session.id == curr_session.id).one_or_none()
        if session is None:
            raise AppException(f'修改的数据可能已不存在!')
        session.session = curr_session.session
        session.begin_date = curr_session.begin_date
        session.end_date = curr_session.end_date
        session.weeksum = curr_session.weeksum
        session.update_time = datetime.datetime.now()
        session.update_by = curr_session.update_by
        db.session.commit()

    @staticmethod
    def find_week():
        cur_session_date = datetime.datetime.now()
        session = Session.query.filter(and_(
            Session.begin_date <= cur_session_date,
            Session.end_date >= cur_session_date
        )).order_by(Session.create_time).first()
        return session.weeksum
